﻿

using DynamicCode;
using DynamicCode.Compilation;
using System;
using System.Linq;

namespace ConsoleApp1
{
    public class Simple2
    {
        internal static void Run()
        {
            DynamicCodeMultipleParameterBuilder dynamicWorker = new DynamicCodeMultipleParameterBuilder(codetemplate, parameterInfos);
            Type[] types = dynamicWorker.Grenerate(dBEntities.Select(n => new DynamicCodeItem { Code = n.Code, Content = n.Content }).ToArray());
            ProductEntity entity = new ProductEntity() { Price = 9, Quantity = 5 };
            ProductDiscountEntity discount = new ProductDiscountEntity() { Discount = 1.3m };
            var instances = types.Select(n => System.Activator.CreateInstance(n)).OfType<IWorker2>();

            Console.WriteLine("Init Moeny:{0} Quantity:{1} Tax:{2}", entity.Moeny, entity.Quantity, entity.Tax);

            foreach (var instance in instances)
            {
                instance.Invoke(entity, discount);
                Console.WriteLine("Run {3} after:\r\n       Moeny:{0} Quantity:{1} Tax:{2}", entity.Moeny, entity.Quantity, entity.Tax, instance.GetType().Name);
            }
        }
        readonly static DynamicCodeParameterInfo[] parameterInfos = new DynamicCodeParameterInfo[] {
            new DynamicCodeParameterInfo{  Name="product", ParameterType=typeof(ProductEntity)},
            new DynamicCodeParameterInfo{  Name="discount", ParameterType=typeof(ProductDiscountEntity)},
            };
        const string codetemplate = @" 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static DynamicCode.ExeclFunctons;  

        public class @code@Worker:ConsoleApp1.IWorker2
        {
            public void Invoke(ConsoleApp1.ProductEntity product, ConsoleApp1.ProductDiscountEntity discount)
            {
                @content@
                
            }
        }
 
";
        static DBEntity[] dBEntities = new[]{
                    new  DBEntity(){Code = "A1",Content = "@product.Moeny@ = @product.Quantity@ + @product.Price@ ;\r\n@product.Tax@ = 3 ; "},
                    new  DBEntity(){Code = "C1",Content = "@product.Moeny@ += @product.Quantity@ +  ROUND( @product.Price@ * @discount.Discount@ ,2);"}
                };
    }
    public interface IWorker2
    {
        void Invoke(ProductEntity product, ProductDiscountEntity discount);
    }
}
